﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using cashbook_psql_cs;
using cashbook_psql_cs.BLL;
using Npgsql;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace cashbook_mg
{
    public partial class FrmStat : Form
    {
        private const int MONTHS_IN_YEAR = 12;
        private readonly RelationBillBLL _billBll = new RelationBillBLL();
        public FrmStat()
        {
            InitializeComponent();
            CenterToScreen();
            // 确保事件绑定（如果设计器未绑定）
            chart1.MouseClick += chart1_MouseClick;
            chart1.MouseMove += chart1_MouseMove;
        }


        private void Form4_Load(object sender, EventArgs e)
        {
            LoadFinancialData(DateTime.Now.Year);
        }

        private void LoadFinancialData(int year)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                // Get data
                var (incomes, expenses) = GetMonthlyFinancialData(year);

                // Display chart
                DisplayChartData(incomes, expenses);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"数据加载失败: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private (double[], double[]) GetMonthlyFinancialData(int year)
        {
            double[] incomes = new double[MONTHS_IN_YEAR];
            double[] expenses = new double[MONTHS_IN_YEAR];

            // Improved SQL query:
            // 1. Filter by year more efficiently
            // 2. Extract month directly
            // 3. Use parameterized queries
            string sqlTemplate = @"SELECT 
                          EXTRACT(MONTH FROM sztime) AS month, 
                          SUM(amount) AS total_amount 
                          FROM relation_bill 
                          WHERE EXTRACT(YEAR FROM sztime) = @year 
                          AND sztype = @type 
                          GROUP BY EXTRACT(MONTH FROM sztime) 
                          ORDER BY month";
            // Get income data
            using (var reader = _billBll.GetMonthlyData(sqlTemplate, year, "收入"))
            {
                while (reader.Read())
                {
                    // Safe reading with type conversion
                    int month = Convert.ToInt32(reader["month"]);  // Or reader.GetInt32(0)
                    double amount = reader.IsDBNull(1) ? 0 : Convert.ToDouble(reader["total_amount"]);
                    incomes[month - 1] = amount;
                }
            }

            // Get expense data
            using (var reader = _billBll.GetMonthlyData(sqlTemplate, year, "支出"))
            {
                while (reader.Read())
                {
                    int month = Convert.ToInt32(reader["month"]);
                    double amount = reader.IsDBNull(1) ? 0 : Convert.ToDouble(reader["total_amount"]);
                    expenses[month - 1] = amount;
                }
            }

            return (incomes, expenses);
        }

        private int GetMonthFromString(string yearMonth)
        {
            return int.Parse(yearMonth.Substring(5, 2)); // Extract MM from YYYY-MM
        }

        private void DisplayChartData(double[] incomes, double[] expenses)
        {
            // Initialize chart
            chart1.ChartAreas.Clear();
            ChartArea chartArea = new ChartArea("FinancialData")
            {
                AxisX = {
                    Title = "月份",
                    MajorGrid = { Enabled = false },
                    Interval = 1
                },
                AxisY = {
                    Title = "金额",
                    MajorGrid = {
                        Enabled = true,
                        LineDashStyle = ChartDashStyle.Dash
                    }
                }
            };
            chart1.ChartAreas.Add(chartArea);
            chart1.Series.Clear();

            // Add income series
            AddChartSeries("收入", incomes, Color.Green);

            // Add expense series
            AddChartSeries("支出", expenses, Color.Red);

            // Configure legend
            chart1.Legends[0].Docking = Docking.Top;
            chart1.Update();
        }

        private void AddChartSeries(string seriesName, double[] values, Color color)
        {
            Series series = new Series(seriesName)
            {
                ChartType = SeriesChartType.Column,
                LegendText = seriesName,
                IsValueShownAsLabel = true,
                Color = color,
                XValueType = ChartValueType.Int32
            };

            for (int i = 0; i < values.Length; i++)
            {
                DataPoint point = new DataPoint(i + 1, values[i])
                {
                    Tag = Tuple.Create(i + 1, seriesName) // Store month and type for click events
                };
                series.Points.Add(point);
            }

            chart1.Series.Add(series);
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            int selectYear = DateTimePicker1.Value.Year;
            LoadFinancialData(selectYear);
        }

       

        private void MenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        

        private void Panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        

        private void DateTimePicker1_ValueChanged(object sender, EventArgs e)
        {

        }

        private void Button2_Click(object sender, EventArgs e)
        {
            this.Visible = false;
        }

        private void panel3_Paint(object sender, PaintEventArgs e)
        {

        }

        private void chart1_MouseMove(object sender, MouseEventArgs e)
        {
            // Debug point for testing
            Console.WriteLine("Chart MouseMove event triggered");
            //Debug.WriteLine("Chart click event triggered");
            HitTestResult result = chart1.HitTest(e.X, e.Y);

            if (result.ChartElementType == ChartElementType.DataPoint)
            {
                DataPoint point = result.Series.Points[result.PointIndex];
                int month = (int)point.XValue;
                double amount = point.YValues[0];
                string type = result.Series.Name;

                // 高亮显示当前数据点
                point.Color = type == "收入" ? Color.LightGreen : Color.OrangeRed;

                // 显示自定义ToolTip
                string tooltipText = $"{type}详情{Environment.NewLine}" +
                                    $"月份: {month}月{Environment.NewLine}" +
                                    $"金额: {amount:C0}";

                toolTip1.SetToolTip(chart1, tooltipText);
            }
            else
            {
                // 恢复所有数据点颜色
                foreach (var series in chart1.Series)
                {
                    foreach (DataPoint p in series.Points)
                    {
                        p.Color = series.Name == "收入" ? Color.Green : Color.Red;
                    }
                }

                toolTip1.SetToolTip(chart1, "");
            }
        }

        private void chart1_MouseClick(object sender, MouseEventArgs e)
        {
            // Debug point for testing
            Console.WriteLine("Chart MouseClick event triggered");
            //Debug.WriteLine("1111111111111111111");
            HitTestResult result = chart1.HitTest(e.X, e.Y);

            if (result.ChartElementType == ChartElementType.DataPoint)
            {
                DataPoint point = result.Series.Points[result.PointIndex];

                // 安全地获取 Tag 值
                if (point.Tag == null)
                {
                    MessageBox.Show("数据点信息未设置", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                try
                {
                    Tuple<int, string> monthYear = (Tuple<int, string>)point.Tag;
                    int month = monthYear.Item1;
                    string type = monthYear.Item2;
                    int year = DateTimePicker1.Value.Year;

                    LoadMonthDetails(year, month, type);
                }
                catch (InvalidCastException)
                {
                    MessageBox.Show("数据点信息格式不正确", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void LoadMonthDetails(int year, int month, string type)
        {
            RelationBillBLL relationBillBLL = new RelationBillBLL();
            try
            {
                // 每次创建新实例
                using (FrmDetail frmDetail = new FrmDetail())
                {
                    // 获取数据并转换为 BindingList
                    BindingList<RelationBill> detailsList = new BindingList<RelationBill>(
                       relationBillBLL.GetDetailsByMonth(year, month, type)
                    );

                    // 使用 BindingSource
                    BindingSource bs = new BindingSource();
                    bs.DataSource = detailsList;
                    frmDetail.PublicDataGridView.DataSource = bs;

                    // 显示模态窗口
                    frmDetail.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载详细数据时出错: {ex.Message}");
            }
        }

        private void toolTip1_Popup(object sender, PopupEventArgs e)
        {

        }

        private void chart1_MouseClick_1(object sender, MouseEventArgs e)
        {

        }
    }
}
